<template>
  <div class="category-management">
    <div class="category-list">
      <el-table :data="categories" style="width: 100%">
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editCategory(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="category-form" v-if="categoryFormVisible">
      <el-divider content-position="left">{{ categoryDialogType === 'create' ? '新增分类' : '编辑分类' }}</el-divider>
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称" required>
          <el-input v-model="categoryForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="categoryForm.description"></el-input>
        </el-form-item>
        <el-form-item label="标签颜色">
          <el-select v-model="categoryForm.type" placeholder="选择颜色">
            <el-option label="默认" value=""></el-option>
            <el-option label="蓝色" value="primary"></el-option>
            <el-option label="绿色" value="success"></el-option>
            <el-option label="黄色" value="warning"></el-option>
            <el-option label="红色" value="danger"></el-option>
            <el-option label="灰色" value="info"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveCategory">保存</el-button>
          <el-button @click="categoryFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="category-actions" v-else>
      <el-button type="primary" @click="createCategory">新增分类</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  categories: {
    type: Array,
    required: true
  },
  projects: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:categories'])

// 分类表单显示状态
const categoryFormVisible = ref(false)
// 分类对话框类型：create-创建，edit-编辑
const categoryDialogType = ref('create')
// 当前编辑的分类ID
const currentCategoryId = ref(null)

// 分类表单
const categoryForm = reactive({
  name: '',
  description: '',
  type: ''
})

// 创建分类
const createCategory = () => {
  categoryDialogType.value = 'create'
  currentCategoryId.value = null
  // 重置表单
  Object.assign(categoryForm, {
    name: '',
    description: '',
    type: ''
  })
  categoryFormVisible.value = true
}

// 编辑分类
const editCategory = (category) => {
  categoryDialogType.value = 'edit'
  currentCategoryId.value = category.id
  // 填充表单
  Object.assign(categoryForm, {
    name: category.name,
    description: category.description,
    type: category.type
  })
  categoryFormVisible.value = true
}

// 删除分类
const deleteCategory = (category) => {
  // 检查是否有项目使用该分类
  const hasProjects = props.projects.some(p => p.categoryId === category.id)

  if (hasProjects) {
    ElMessage.warning('该分类下有项目，无法删除')
    return
  }

  ElMessageBox.confirm(`确定要删除分类"${category.name}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行删除操作
    const updatedCategories = props.categories.filter(c => c.id !== category.id)
    emit('update:categories', updatedCategories)
    ElMessage.success('分类已删除')
  }).catch(() => {
    // 取消操作
  })
}

// 保存分类
const saveCategory = () => {
  // 表单验证
  if (!categoryForm.name) {
    ElMessage.warning('请填写分类名称')
    return
  }

  // 构建分类数据
  const categoryData = {
    name: categoryForm.name,
    description: categoryForm.description,
    type: categoryForm.type
  }

  // 复制现有分类数组
  const updatedCategories = [...props.categories]

  if (categoryDialogType.value === 'create') {
    // 创建新分类
    categoryData.id = Date.now() // 简单生成ID
    updatedCategories.push(categoryData)
    ElMessage.success('分类创建成功')
  } else {
    // 更新现有分类
    const index = updatedCategories.findIndex(c => c.id === currentCategoryId.value)
    if (index !== -1) {
      categoryData.id = currentCategoryId.value
      updatedCategories[index] = categoryData
      ElMessage.success('分类更新成功')
    }
  }

  // 更新父组件中的分类数据
  emit('update:categories', updatedCategories)
  categoryFormVisible.value = false
}
</script>

<style scoped>
.category-management {
  width: 100%;
}

.category-list {
  margin-bottom: 20px;
}

.category-form {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.category-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style> 